package com.rpoonolly.simplegame.processors;

import java.util.List;

import javax.vecmath.Vector2d;

import com.rpoonolly.simplegame.core.CollisionDetector;
import com.rpoonolly.simplegame.core.CollisionResponder;
import com.rpoonolly.simplegame.core.aabb.AABBCollision;
import com.rpoonolly.simplegame.core.aabb.AABBEntity;
import com.rpoonolly.simplegame.core.aabb.DynamicAABBEntity;
import com.rpoonolly.simplegame.core.aabb.EntityGameMap;

/**
 * @author Ryan
 * 
 * simple processor for dynamic entities. Has functionalities useful for implementing classes.
 */
public abstract class DynamicEntityProcessor extends EntityProcessor<AABBEntity> {
	
	/**
	 * collision detector used for this character processor
	 */
	protected CollisionDetector<AABBEntity, AABBCollision> collisionDetector;
	
	/**
	 * collision responder used for this character processor
	 */
	protected CollisionResponder<AABBCollision> collisionResponder;
	
	/**
	 * last time process was called
	 */
	protected long lastTime;
	
	/**
	 * time delta since last process call
	 */
	protected double dt;
	
	public DynamicEntityProcessor(
		CollisionDetector<AABBEntity, AABBCollision> detector, 
		CollisionResponder<AABBCollision> responder,
		EntityGameMap<AABBEntity> gameMap
	) {
		super(gameMap);
		collisionDetector = detector;
		collisionResponder = responder;
	}
	
	/**
	 * Records the time since last process call in member dt
	 */
	protected void processTime() {
		if (lastTime == 0) lastTime = System.currentTimeMillis();
		dt = System.currentTimeMillis() - lastTime;
		lastTime += dt;
	}
	
	/**
	 * gets the first collision against the given list of collidables
	 * 
	 * @param dynamicEntity dynamic entity to check movement against (uses it's getDirection() function to see it's movement)
	 * @param collidables list of entities that can be collided with
	 * @return the collision object encapsulating collision information
	 */
	protected AABBCollision checkGroupCollision(DynamicAABBEntity dynamicEntity, List<AABBEntity> collidables) {
		Vector2d v = dynamicEntity.getDirection();
		AABBCollision collision, minCollision = null;
		
		for (AABBEntity entity : collidables) {
			if (dynamicEntity == entity) continue;
			collision = collisionDetector.collisionDetect(entity, dynamicEntity, v);
			
			if (collision == null) continue;
			else if (minCollision == null) minCollision = collision;
			else if (collision.compareTo(minCollision) < 0) {
				minCollision = collision;
				v = minCollision.getMovementVector();
			}
		}
		
		return minCollision;
	}
}
